//
//  PasswordViewController.m
//  Contractor
//
//  Created by 金鑫 on 16/5/18.
//  Copyright © 2016年 star j. All rights reserved.
//

#import "PasswordViewController.h"
#import "CONST.h"
#import "PasswordField.h"

@interface PasswordViewController ()<UITextFieldDelegate>
{
    PasswordField *oldPwdField ;
    PasswordField *NewPwdField ;
    PasswordField *doPwdField ;
    PasswordField *YzField ;
    UIButton *yanzhengBtn ;
    UIImageView *Yzline ;
    UIButton *saveBtn ;
}
@end

@implementation PasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor] ;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
    [self createView] ;
}

- (void)createView
{
    CGSize LabelLength = [self lengthwithLabel:@"这有五个字" withsize:16.0f] ;
    CGRect oldpwdFrame = CGRectMake(10, 17, LabelLength.width, 18.0f) ;
    CGRect newpwdFrame = CGRectMake(10, 17+50, LabelLength.width, 18.0f) ;
    CGRect dopwdFrame = CGRectMake(10, 17+100, LabelLength.width, 18.0f) ;
    CGRect YzFrame = CGRectMake(10, 17+150, LabelLength.width, 18.0f) ;
    [self creatLabel:@"旧密码" frame:oldpwdFrame size:16.0f] ;
    [self creatLabel:@"新密码" frame:newpwdFrame size:16.0f] ;
    [self creatLabel:@"确认密码" frame:dopwdFrame size:16.0f] ;
    [self creatLabel:@"手机验证码" frame:YzFrame size:16.0f] ;
    for (int i = 0; i < 4; i++) {
        CGRect frame = CGRectMake(0, 50*(i+1), __kScreenWidth, 0.5) ;
        [self createline:frame] ;
    }
    
    CGRect field1 = CGRectMake(LabelLength.width + 20, 5, LabelLength.width*2, 40) ;
    CGRect field2 = CGRectMake(LabelLength.width + 20, 5+50, LabelLength.width*2, 40) ;
    CGRect field3 = CGRectMake(LabelLength.width + 20, 5+100, LabelLength.width*2, 40) ;
    CGRect field4 = CGRectMake(LabelLength.width + 20, 5+150, LabelLength.width, 40) ;
    
    
    oldPwdField = [self createTextfield:@"旧密码" frame:field1 alignment:NSTextAlignmentLeft] ;
    NewPwdField = [self createTextfield:@"6-12位数字和字母" frame:field2 alignment:NSTextAlignmentLeft] ;
    doPwdField = [self createTextfield:@"6-12位数字和字母" frame:field3 alignment:NSTextAlignmentLeft] ;
    YzField = [self createTextfield:@"验证码" frame:field4 alignment:NSTextAlignmentLeft] ;
    [self.view addSubview:oldPwdField] ;
    [self.view addSubview:NewPwdField] ;
    [self.view addSubview:doPwdField] ;
    [self.view addSubview:YzField] ;
    
    UIImageView *line2 = [[UIImageView alloc] initWithFrame:CGRectMake(field4.origin.x + field4.size.width + 30, 10+150, 0.5, 30)] ;
    [line2 setImage:[UIImage imageNamed:@"password_alter_auth_code_divide_line.png"]] ;
    [self.view addSubview:line2] ;
    
    //验证按钮
    yanzhengBtn = [[UIButton alloc] initWithFrame:CGRectMake(line2.frame.origin.x + 30, 150, LabelLength.width, 50)] ;
    [yanzhengBtn setTitle:@"获取验证码" forState:UIControlStateNormal] ;
    [yanzhengBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal] ;
    yanzhengBtn.titleLabel.font = [UIFont systemFontOfSize: 16.0f] ;
    yanzhengBtn.titleLabel.textAlignment = NSTextAlignmentCenter ;
    
    yanzhengBtn.backgroundColor = [UIColor clearColor] ;
    yanzhengBtn.layer.backgroundColor = [UIColor clearColor].CGColor ;
    [yanzhengBtn addTarget:self action:@selector(yanzheng) forControlEvents:UIControlEventTouchUpInside] ;
    [self.view addSubview:yanzhengBtn] ;
    
    Yzline = [[UIImageView alloc] initWithFrame:CGRectMake(line2.frame.origin.x + 30, 182, LabelLength.width, 1)] ;
    [Yzline setImage:[UIImage imageNamed:@"order_details_status_line.png"]] ;
    [self.view addSubview:Yzline] ;
    
    saveBtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - LabelLength.width*2+10)/2, 230, LabelLength.width*2-10, 50)] ;
    [saveBtn setTitle:@"保存修改" forState:UIControlStateNormal] ;
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] ;
    saveBtn.backgroundColor = [UIColor blueColor] ;
    saveBtn.layer.cornerRadius = 5.0f ;
    [saveBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside] ;
    [self.view addSubview:saveBtn] ;
}

- (void)save
{
    [oldPwdField resignFirstResponder] ;
    [NewPwdField resignFirstResponder] ;
    [doPwdField resignFirstResponder] ;
    [YzField resignFirstResponder] ;
    
    if (oldPwdField.text.length == 0) {
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 130)/2, __kScreenHeight - 70, 130, 40)] ;
        [errorbtn setTitle:@"请输入原始密码！" forState:UIControlStateNormal] ;
        errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:14.0f] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor blackColor] ;
        errorbtn.alpha = 0.8 ;
        //[self.view addSubview:errorbtn] ;
        [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
    }
    else if (NewPwdField.text.length > 12 || NewPwdField.text.length < 6)
    {
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 160)/2, __kScreenHeight - 70, 160, 40)] ;
        [errorbtn setTitle:@"请输入合适的密码长度！" forState:UIControlStateNormal] ;
        errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:14.0f] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor blackColor] ;
        errorbtn.alpha = 0.8 ;
        //[self.view addSubview:errorbtn] ;
        [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
    }
    else if (![doPwdField.text isEqualToString:NewPwdField.text])
    {
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 130)/2, __kScreenHeight - 70, 130, 40)] ;
        [errorbtn setTitle:@"新密码输入不一致！" forState:UIControlStateNormal] ;
        errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:14.0f] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor blackColor] ;
        errorbtn.alpha = 0.8 ;
        //[self.view addSubview:errorbtn] ;
        [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
    }
    else if (YzField.text.length == 0)
    {
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 130)/2, __kScreenHeight - 70, 130, 40)] ;
        [errorbtn setTitle:@"请输入验证码！" forState:UIControlStateNormal] ;
        errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:14.0f] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor blackColor] ;
        errorbtn.alpha = 0.8 ;
        //[self.view addSubview:errorbtn] ;
        [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
    }
    else
    {
        NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
        NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
        
        NSNumber *cmd = [[NSNumber alloc] initWithInt:303] ;
        NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;

        NSDictionary *jsondic = @{
                                  @"oldpassword":oldPwdField.text,
                                  @"newpassword":NewPwdField.text,
                                  @"renewpassword":doPwdField.text,
                                  @"editpasswordverify":YzField.text
                                  } ;
        NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
        NSLog(@"%@",jsondic) ;
        NSLog(@"%@",jsonstr) ;
        NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
        NSLog(@"%@",parameters) ;
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             //解密并解析json数据，将json转成字典
             NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
             NSLog(@"decodeStr:%@",decodeStr) ;
             decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
             NSLog(@"decodeStr:%@",decodeStr) ;
             NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
             id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
             //获取字典中的值
             if ([result isKindOfClass:[NSDictionary class]])
             {
                 NSDictionary *dic = result ;
                 NSLog(@"msg:%@",dic[@"msg"]) ;
                 UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 100)/2, __kScreenHeight - 70, 100, 40)] ;
                 [errorbtn setTitle:dic[@"msg"] forState:UIControlStateNormal] ;
                 errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:14.0f] ;
                 errorbtn.layer.cornerRadius = 10 ;
                 errorbtn.backgroundColor = [UIColor blackColor] ;
                 errorbtn.alpha = 0.8 ;
                 //[self.view addSubview:errorbtn] ;
                 [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
                 [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
                 if ([dic[@"status"] integerValue] == 1) {
                     [self.navigationController popViewControllerAnimated:NO] ;
                 }
             }
         }
              failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             NSLog(@"Error: %@", error);
         }];

    }
}

#pragma mark - 创建textfield
- (PasswordField *)createTextfield:(NSString *)title frame:(CGRect)frame alignment:(NSTextAlignment)alignment
{
    PasswordField *textfield = [[PasswordField alloc] initWithFrame:frame] ;
    textfield.placeholder = title ;
    textfield.delegate = self ;
    textfield.keyboardType = UIKeyboardTypeDefault ;
    textfield.secureTextEntry = YES ;
    textfield.backgroundColor=[UIColor whiteColor];
    textfield.layer.borderColor = [UIColor blackColor].CGColor ;
    textfield.layer.borderWidth = 1.0f ;
    textfield.layer.cornerRadius = 4.0f ;
    textfield.adjustsFontSizeToFitWidth=YES;//自适应宽度
    //设置UITextField的边框的风格
    textfield.borderStyle=UITextBorderStyleNone;
    textfield.textAlignment = alignment ;
    return textfield ;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder] ;
    return YES ;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [oldPwdField resignFirstResponder] ;
    [NewPwdField resignFirstResponder] ;
    [doPwdField resignFirstResponder] ;
    [YzField resignFirstResponder] ;
}

- (void)createline:(CGRect)frame
{
    UIImageView *line = [[UIImageView alloc] initWithFrame:frame] ;
    [line setImage:[UIImage imageNamed:@"layout_small_line_bg.png"]] ;
    [self.view addSubview:line] ;
}


- (void)creatLabel:(NSString *)titile frame:(CGRect )frame size:(CGFloat)size
{
    UILabel *Label = [[UILabel alloc] init] ;
    Label.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:size] ;
    Label.backgroundColor = [UIColor clearColor] ;
    Label.text = titile ;
    Label.textAlignment = NSTextAlignmentLeft ;
    Label.textColor = [UIColor blackColor] ;
    Label.frame = frame ;
    [self.view addSubview:Label] ;
}

- (CGSize)lengthwithLabel:(NSString *)lable withsize:(CGFloat) size
{
    NSDictionary *attribute1 = @{NSFontAttributeName: [UIFont fontWithName:@"AvenirLTStd-Light" size:size]};
    CGSize DescSize = [lable boundingRectWithSize:CGSizeMake(MAXFLOAT, size) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute1 context:nil].size;
    return DescSize ;
}


#pragma mark - 请求验证码
- (void)yanzheng
{
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:302] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSDictionary *parameters = @{@"cmd":cmd,@"uid":uid};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr1:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             // NSLog(@"dic:%@",dic) ;
             if ([dic[@"status"] integerValue] == 1)
             {
                 [self timenum] ;
             }
             
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@", error);
     }];
}


#pragma mark - 验证码倒计时
- (void)timenum
{
    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            yanzhengBtn.enabled = YES ;
            dispatch_source_cancel(_timer);
            //dispatch_release(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                yanzhengBtn.titleLabel.text = @"获取验证码" ;
                yanzhengBtn.titleLabel.textColor = [UIColor blueColor] ;
                [self.view addSubview:Yzline] ;
            });
        }else{
            yanzhengBtn.enabled = NO ;
            //            int minutes = timeout / 60;
            //            int seconds = timeout % 60;
            NSString *strTime = nil ;
            if (timeout >= 10) {
                strTime = [NSString stringWithFormat:@" 还剩%lds",(long)timeout];
            }
            else
            {
                strTime = [NSString stringWithFormat:@"  还剩%lds",(long)timeout];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                yanzhengBtn.titleLabel.text = strTime ;
                yanzhengBtn.titleLabel.textColor = [UIColor redColor] ;
                [Yzline removeFromSuperview] ;
                //zhuceBtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:16.0f] ;
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
}

- (void)clearbtn:(id)sender
{
    saveBtn.enabled = YES ;
    [sender removeFromSuperview] ;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
